﻿#pragma once
#include "stdafx.h"
#include <initializer_list>
#include <functional>
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class List
{
public:
	List()
	{}

	List(ListNode* l)
	{
		m_pHead = l;
		if (l == nullptr)
			return;
		m_size = 0;
		IterateItems([&](ListNode* p)
		{
			m_pTail = p;
			m_size++;
		});
	}

	//通过初始化列表构造List对象，使用此构造函数构造的对象需要调用Destroy()来析构
	List(const std::initializer_list<int>& paras)
	{
		for (const auto& para : paras)
		{
			ListNode* pNode = new ListNode(para);
			if (m_pHead == nullptr)
				m_pHead = pNode;
			else
				m_pTail->next = pNode;
			m_pTail = pNode;
		}
		m_size = paras.size();
	}

	//析构列表所有节点
	void Destroy()
	{
		ListNode* p = m_pHead;
		ListNode* pDeleted = m_pHead;
		while (p != nullptr)
		{
			pDeleted = p;
			p = p->next;
			delete pDeleted;
		}
		m_pHead = nullptr;
		m_pTail = nullptr;
	}

	void Clone(const List& list1)
	{
		Destroy();
		list1.IterateItems([&](ListNode* p)
		{
			ListNode* pNode = new ListNode(p->val);
			if (m_pHead == nullptr)
				m_pHead = pNode;
			else
				m_pTail->next = pNode;
			m_pTail = pNode;

		});
	}

	void Swap(List& list1)
	{
		List temp = *this;
		*this = list1;
		list1 = temp;
	}

	int Size()
	{
		return m_size;
	}

	ListNode* GetHead()
	{
		return m_pHead;
	}

	void IterateItems(std::function<void(ListNode*)> func) const           //遍历所有节点
	{
		ListNode* p = m_pHead;
		while (p != nullptr)
		{
			func(p);
			p = p->next;
		}
	}

	void Output()
	{
		IterateItems([](ListNode* pNode)
		{
			std::cout << pNode->val << ", ";
		});
		std::cout << std::endl;
	}

private:
	ListNode* m_pHead{};
	ListNode* m_pTail{};
	int m_size{};
};

class Solution {
public:
	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		List list1{ l1 };
		List list2{ l2 };
		if (list1.Size() < list2.Size())
			list1.Swap(list2);
		List list_new;
		list_new.Clone(list1);

	}

public:
};

void TestAddTowNumbersII()
{
	List list{ 1,2,3,4 };
	List list2;
	list2.Clone(list);
	list2.Output();
	list.Output();

}